var express = require("express");
var router = express.Router();
// 引入fs文件系统和multer进行头像文件上传,具体的需要查看文档
var fs = require("fs");
var multer = require("multer");
// 这个storage会预先对传来的图片进行处理，在这里就已经将图片存储在本地了，后面只不过是将图片在本地的链接地址传出去罢了
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        //指定文件路径存储地
        cb(null, "./public/uploads/");
    },
    filename: function (req, file, cb) {
        //指定存储后的文件名(有两个问题)
        //1文件名重复覆盖  时间戳
        //2后缀名发生改变
        console.log("---", file);
        //获取后缀名
        let exts = file.originalname.split(".");
        console.log("---", exts);
        // 这是上传文件的后缀
        let ext = exts[exts.length - 1];
        let tepname = new Date().getTime() + parseInt(Math.random() * 9999);
        //拼接名字
        cb(null, `${tepname}.${ext}`);
    },
});

let upload = multer({
    storage: storage,
});
// 有点意外这里的输出目录是从根目录开始的，不是本文件的相对路径
// let upload = multer({ dest: "./public/uploads/" }).single("file");

// var bodyParser = require("body-parser");
const code = require("../controllers/userController");
const aliTextMsg = require("../controllers/sendTextMsg");
const phoneLogin = require("../controllers/phoneLogin");
const { route } = require(".");
/* GET users listing. */
router.get("/", function (req, res, next) {
    res.send("respond with a resource");
});
// 这是一个进行测试的接口，测试在formdata或json格式上传文件，可以在req.body里面获取到
router.post("/send", upload.single("file"), function (req, res) {
    if (req.body.cheng === undefined && req.cheng == undefined) {
        res.send({ msg: "文件不能为空" });
    } else {
        console.log("req:", req);
        let data = req.body.cheng;
        // 注意file是直接在req里面获得，而不是req.body里面
        let file = req.file;
        res.send({ msg: data, file: file || "null", id: req.query });
    }
});

router.post("/uploadimg", upload.single("file"), function (req, res, next) {
    console.log("req", req);
    let { size, mimetype, path } = req.file;
    console.log(mimetype);
    let types = ["jpeg", "jpg", "png", "gif"]; //允许上传的类型
    let tmpType = mimetype.split("/")[1];

    console.log(tmpType);
    if (size > 5000000) {
        return res.send({ err: -1, msg: "上传的内容不能超过5000000" });
    } else if (types.indexOf(tmpType) == -1) {
        return res.send({ err: -2, msg: "上传的类型错误" });
    } else {
        // 实际上在app.js里面：app.use(express.static(path.join(__dirname, 'public')))
        let url = `/uploads/${req.file.filename}`;
        res.send({ err: 0, msg: "上传成功", img: url });
        // 最后的实际访问为：http://api.chengsong.info/uploads/751898925b330af2567b19506a50b01c.jpg
    }
});

router.post("/sendcode", code.sendcode);
router.post("/codelogin", code.codeLogin);
router.post("/phonelogin", phoneLogin.phoneLogin);
router.post("/sendcorecode", aliTextMsg.sendCoreCode);
module.exports = router;
